const Koa = require('koa')
const app = new Koa()
const views = require('koa-views')
const json = require('koa-json')
const common = require('./routes/common')
const logger = require('koa-logger')
var cors = require('koa2-cors');
const index = require('./routes/index')
const user = require('./routes/user')
const { koaBody } = require("koa-body");
const { wssrouter } = require("./routes/wss")
require("./utils/db")
const path = require("path");




app.use(async (ctx, next) => {
  try {
    await next();
  } catch (err) {
    ctx.set("Access-Control-Allow-Origin", "*");
    ctx.set("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE");
    ctx.set("Access-Control-Allow-Headers", "Content-Type");
    ctx.status = err.status || 202; // Default to 500 if no status set
    ctx.body = {
      message: err.message || 'Internal Server Error',
      code: ctx.status,
    };
  }
})

// middlewares
app.use(cors()).use(
  koaBody({
    multipart: true, //解析多个文件
    formidable: {
      maxFileSize: 100 * 1024 * 1024, // 设置上传文件大小最大限制，默认2M
      uploadDir: path.join(__dirname, `public/upload/wxfile`), // 设置文件上传目录
      keepExtensions: true,
      onFileBegin: (name, file) => {

        const dir = path.join(__dirname, `public/upload/wxfile`);
        if (name === 'wxfile') {
          // file.filepath = `${dir}/${file.originalFilename}`;
        }

      }
    },
  })
)

  .use(json())
  .use(logger())
  .use(require('koa-static')(__dirname + '/public/upload/wxfile'), {

    setHeaders: (res, path, stat) => {
      const isCacheable = /\.(css|js|jpe?g|png|gif|svg|woff|woff2)$/i.test(path);
      if (isCacheable) {
        res.setHeader('Cache-Control', `public, max-age=${60 * 60 * 24 * 7}`);
        res.setHeader('Expires', new Date(Date.now() + 60 * 60 * 24 * 7 * 1000).toUTCString());
      }
    }
  })
  .use(require('koa-static')(__dirname + '/public'))
  .use(require('koa-static')(__dirname + '/views/chat'))
  // app.use(require('koa-static')(__dirname + '/public'))
  .use(views(__dirname + '/views', {
    extension: 'ejs'
  }))
  // routes
  .use(index.routes(), index.allowedMethods())
  .use(user.routes(), user.allowedMethods())
  .use(common.routes(), common.allowedMethods())
  .use(wssrouter.routes(), wssrouter.allowedMethods())


module.exports = app
